package com.czy.booktest02.demos.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.czy.booktest02.demos.common.dtos.ResponseResult;
import com.czy.booktest02.demos.common.enums.AppHttpCodeEnum;
import com.czy.booktest02.demos.exception.GlobalException;
import com.czy.booktest02.demos.mapper.BookFileMapper;
import com.czy.booktest02.demos.mapper.BookMapper;
import com.czy.booktest02.demos.pojo.dto.BookFileDto;
import com.czy.booktest02.demos.pojo.po.BookFile;
import com.czy.booktest02.demos.pojo.po.Books;
import com.czy.booktest02.demos.pojo.vo.FileVO;
import com.czy.booktest02.demos.service.BookFileService;
import com.czy.booktest02.demos.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.sql.Wrapper;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static com.czy.booktest02.demos.constant.ResultStatus.HTTPSERVER_SYSTEM_EXCEPTION;

@Service
public class BookFileServiceImpl implements BookFileService {
    @Autowired
    private BookFileMapper bookFileMapper;
    @Autowired
    private BookMapper bookMapper;

    /**
     * 时间格式化
     */
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");

    /**
     * 图片保存路径
     */
    @Value("${file-save-path}")
    private String fileSavePath;
    @Override
    public ResponseResult uploadPicture(BookFileDto bookFileDto, MultipartFile file, HttpServletRequest request) {
        String directory = simpleDateFormat.format(TimeUtil.getTime());
        /**
         * 文件保存目录 D:/images/
         * 如果目录不存在，则创建
         */
        File dir = new File(fileSavePath + directory);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        System.out.println("图片上传，保存的位置:" + fileSavePath + directory);

        /**
         * 给文件重新设置一个名字
         * 后缀
         */
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;

        //4.创建这个新文件
        File newFile = new File(fileSavePath + directory + newFileName);
        //5.复制操作
        try {
            file.transferTo(newFile);
            //协议 :// ip地址 ：端口号 / 文件目录(/images/xxx.jpg)
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + directory + newFileName;
            System.out.println("文件上传，访问URL：" + url);
            //保存入库,绑定对应书籍
            BookFile bookFile = new BookFile();
            bookFile.setFileName(newFileName);
            bookFile.setFileType(bookFileDto.getType());
            bookFile.setFilePath(url);
            bookFile.setUploadDate(new Date());
            int result = bookFileMapper.addBookFile(bookFile);
            if (result>0) {
                int fileId = bookFile.getId();
                if(bookMapper.updateFileId(bookFileDto.getId(), fileId)>0){
                    return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
                }
            }
        } catch (IOException e) {
            throw new GlobalException(HTTPSERVER_SYSTEM_EXCEPTION,e.toString());
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.FAILURE);
    }

    @Override
    public ResponseResult selectFileRecord(String bookName) {
        if(bookName==null){
            //查询全部
            Page<BookFile> page = new Page<>(0,10);
            QueryWrapper<BookFile> wrapper = new QueryWrapper<>();
            Page<BookFile> result = bookFileMapper.selectPage(page, wrapper);
            return ResponseResult.okResult(result);
        }else{
            //查询一条
            Books book = bookMapper.selectByName(bookName);
            int fileId = book.getFileId();
            BookFile bookFile = bookFileMapper.selectById(fileId);
            return ResponseResult.okResult(bookFile);
        }
    }

    @Override
    public ResponseResult deleteFileRecord(String bookName) {
        int i =0;
        if(bookName==null){
            //删除全部
            i = bookFileMapper.deleteAll();
        }else {
            // 删除单个文件
            Books book = bookMapper.selectByName(bookName);
            int fileId = book.getFileId();
            i = bookFileMapper.deleteById(fileId);
        }
        if(i>0){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return  ResponseResult.errorResult(AppHttpCodeEnum.FAILURE);
    }

    @Override
    public ResponseResult showFileRecord() {
        List<FileVO> fileVOS = bookFileMapper.selectFileRecord();
        if(fileVOS!=null){
            return ResponseResult.okResult(fileVOS);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.FAILURE);
    }
}
